package com.phkj.qdh.ui.fragment.mynotice

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.AdapterView.OnItemClickListener
import androidx.activity.OnBackPressedCallback
import androidx.core.content.ContextCompat
import androidx.fragment.app.commit
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.QuickAdapterHelper
import com.chad.library.adapter4.loadState.LoadState
import com.chad.library.adapter4.loadState.trailing.TrailingLoadStateAdapter
import com.flyco.tablayout.listener.OnTabSelectListener
import com.phkj.qdh.R
import com.phkj.qdh.bean.MyTab
import com.phkj.qdh.bean.PageInfo
import com.phkj.qdh.databinding.FragmentMyNoticeBinding
import com.phkj.qdh.ui.adapter.usercenter.MyBaseInspectAdapter
import com.phkj.qdh.ui.adapter.usercenter.MyLawInspectAdapter
import com.phkj.qdh.ui.adapter.usercenter.MyTeamInspectAdapter
import com.phkj.qdh.ui.fragment.user.UserVM
import com.phkj.qdh.ui.fragment.user.getUserVMProvider
import com.phkj.qdh.utils.LogUtil
import com.phkj.qdh.utils.MyItemDecoration
import com.phkj.qdh.utils.PAGE_SIZE
import com.phkj.qdh.utils.launchAndRepeatWithViewLifecycle
import com.phkj.qdh.utils.node.MyBaseQuickAdapter
import com.phkj.qdh.utils.node.OnItemChildClickListener
import kotlinx.coroutines.flow.collectLatest
import java.util.HashMap

private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * 我的通告
 */
class MyNoticeFragment : Fragment() {
    private var param1: String? = null
    private var param2: String? = null
    private var _binding: FragmentMyNoticeBinding? = null
    private val binding get() = _binding!!
    private var pos = 0
    private lateinit var baseHelper: QuickAdapterHelper
    private lateinit var teamHelper: QuickAdapterHelper
    private lateinit var lawHelper: QuickAdapterHelper
    private val myBaseInspectAdapter by lazy { MyBaseInspectAdapter() }
    private val myTeamInspectAdapter by lazy { MyTeamInspectAdapter() }
    private val myLawInspectAdapter by lazy { MyLawInspectAdapter() }
    private val basePageInfo = PageInfo()
    private val teamPageInfo = PageInfo()
    private val lawPageInfo = PageInfo()
    private lateinit var vm: UserVM
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
        requireActivity().onBackPressedDispatcher.addCallback(this,
            object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    parentFragmentManager.popBackStack()
                }
            })
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentMyNoticeBinding.inflate(inflater, container, false)
        vm = ViewModelProvider(this, getUserVMProvider())[UserVM::class.java]
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initAdapter()
        binding.run {
            ivBack.setOnClickListener {
                parentFragmentManager.popBackStack()
            }
            rvUseCar.run {
                layoutManager = LinearLayoutManager(requireContext())
                addItemDecoration(MyItemDecoration(width = 22))
            }
            ctl.run {
                setTabData(arrayListOf(MyTab("基础"), MyTab("队伍"), MyTab("执法")))
                getMsgView(1).backgroundColor =
                    ContextCompat.getColor(requireContext(), R.color.main_color)
                //设置边距
            }
            ctl.setOnTabSelectListener(object : OnTabSelectListener {
                override fun onTabSelect(position: Int) {
                    LogUtil.E("tab选择")
                    when (position) {
                        0 -> {
                            rvUseCar.adapter = baseHelper.adapter
                        }

                        1 -> {
                            rvUseCar.adapter = teamHelper.adapter
                        }

                        else -> {
                            rvUseCar.adapter = lawHelper.adapter
                        }
                    }
                    pos = position
                    refresh()
                }

                override fun onTabReselect(position: Int) {
                    LogUtil.E("tab再次选择")
                    refresh()
                }

            })

            srlUseCar.setOnRefreshListener {
                LogUtil.E("刷新")
                refresh()
            }
        }
        launchAndRepeatWithViewLifecycle {
            vm.state.collectLatest {
                binding.srlUseCar.isRefreshing = false
            }
        }

        launchAndRepeatWithViewLifecycle {
            vm.baseNotice.collectLatest {
                if (basePageInfo.isFirstPage) {
                    myBaseInspectAdapter.submitList(it)
                } else {
                    myBaseInspectAdapter.addAll(it)
                }
                if (it.size != PAGE_SIZE) {
                    baseHelper.trailingLoadState = LoadState.NotLoading(true)
                } else {
                    baseHelper.trailingLoadState = LoadState.NotLoading(false)
                }
            }
        }

        launchAndRepeatWithViewLifecycle {
            vm.teamNotice.collectLatest {
                if (teamPageInfo.isFirstPage) {
                    myTeamInspectAdapter.submitList(it)
                } else {
                    myTeamInspectAdapter.addAll(it)
                }
                if (it.size != PAGE_SIZE) {
                    teamHelper.trailingLoadState = LoadState.NotLoading(true)
                } else {
                    teamHelper.trailingLoadState = LoadState.NotLoading(false)
                }
            }
        }

        launchAndRepeatWithViewLifecycle {
            vm.lawNotice.collectLatest {
                if (lawPageInfo.isFirstPage) {
                    myLawInspectAdapter.submitList(it)
                } else {
                    myLawInspectAdapter.addAll(it)
                }

                if (it.size != PAGE_SIZE) {
                    lawHelper.trailingLoadState = LoadState.NotLoading(true)
                } else {
                    lawHelper.trailingLoadState = LoadState.NotLoading(false)
                }
            }
        }

        getTeamInspect()
        getLawInspect()
        getBaseInspect()
    }

    override fun onResume() {
        super.onResume()
        when (binding.ctl.currentTab) {
            0 -> {
                binding.rvUseCar.adapter = baseHelper.adapter
            }

            1 -> {
                binding.rvUseCar.adapter = teamHelper.adapter
            }

            else -> {
                binding.rvUseCar.adapter = lawHelper.adapter
            }
        }
    }

    private fun initAdapter() {
        baseHelper = QuickAdapterHelper.Builder(myBaseInspectAdapter)
            .setTrailingLoadStateAdapter(object : TrailingLoadStateAdapter.OnTrailingListener {
                override fun onLoad() {
                    basePageInfo.nextPage()
                    getBaseInspect()
                }

                override fun onFailRetry() {
                    getBaseInspect()
                }

                override fun isAllowLoading(): Boolean {
                    return !binding.srlUseCar.isRefreshing
                }
            }).build()

        binding.rvUseCar.adapter = baseHelper.adapter
        myBaseInspectAdapter.addOnItemChildClickListener(R.id.tv) { adapter, _, pos ->
            adapter.getItem(pos)?.let {
                parentFragmentManager.commit {
                    addToBackStack("base_detail")
                    replace(id, MyBaseNoticeDetailFragment.newInstance(it, ""), "")
                    setReorderingAllowed(true)
                }
            }
        }

        teamHelper = QuickAdapterHelper.Builder(myTeamInspectAdapter)
            .setTrailingLoadStateAdapter(object : TrailingLoadStateAdapter.OnTrailingListener {
                override fun onLoad() {
                    teamPageInfo.nextPage()
                    getTeamInspect()
                }

                override fun onFailRetry() {
                    getTeamInspect()
                }

                override fun isAllowLoading(): Boolean {
                    return !binding.srlUseCar.isRefreshing
                }
            }).build()

        myTeamInspectAdapter.addOnItemChildClickListener(R.id.tv) { adapter, _, pos ->
            adapter.getItem(pos)?.let {
                parentFragmentManager.commit {
                    addToBackStack("team_detail")
                    replace(id, MyTeamNoticeDetailFragment.newInstance(it.id, ""), "")
                    setReorderingAllowed(true)
                }
            }
        }


        lawHelper = QuickAdapterHelper.Builder(myLawInspectAdapter)
            .setTrailingLoadStateAdapter(object : TrailingLoadStateAdapter.OnTrailingListener {
                override fun onLoad() {
                    lawPageInfo.nextPage()
                    getLawInspect()
                }

                override fun onFailRetry() {
                    getLawInspect()
                }

                override fun isAllowLoading(): Boolean {
                    return !binding.srlUseCar.isRefreshing
                }
            }).build()

        myLawInspectAdapter.addOnItemChildClickListener(R.id.tv) { adapter, _, pos ->
            adapter.getItem(pos)?.let {
                parentFragmentManager.commit {
                    addToBackStack("team_detail")
                    replace(id, MyLawNoticeDetailFragment.newInstance(it.id, ""), "")
                    setReorderingAllowed(true)
                }
            }
        }
    }

    private fun refresh() {
        when (pos) {
            0 -> {
                basePageInfo.reset()
                baseHelper.trailingLoadState = LoadState.None
                getBaseInspect()
            }

            1 -> {
                teamPageInfo.reset()
                teamHelper.trailingLoadState = LoadState.None
                getTeamInspect()
            }

            else -> {
                lawPageInfo.reset()
                lawHelper.trailingLoadState = LoadState.None
                getLawInspect()
            }
        }
    }


    private fun getBaseInspect() {
        val map = HashMap<String, Any?>()
        map["page"] = basePageInfo.page
        map["size"] = PAGE_SIZE
        vm.getBaseNotice(map)
    }


    private fun getTeamInspect() {
        val map = HashMap<String, Any?>()
        map["page"] = teamPageInfo.page
        map["size"] = PAGE_SIZE
        map["inspectId"] = 3
        vm.getTeamNotice(map)
    }

    private fun getLawInspect() {
        val map = HashMap<String, Any?>()
        map["page"] = lawPageInfo.page
        map["size"] = PAGE_SIZE
        map["inspectId"] = 2
        vm.getLawNotice(map)
    }

    companion object {
        @JvmStatic
        fun newInstance(param1: String, param2: String) = MyNoticeFragment().apply {
            arguments = Bundle().apply {
                putString(ARG_PARAM1, param1)
                putString(ARG_PARAM2, param2)
            }
        }
    }
}